﻿#include "config.h"
#include "aprs.h"

Preferences prefs;
AppConfig cfg;

void loadConfig() {
  prefs.begin("aprs", true);
  cfg.wifiSsid   = prefs.getString("wifiSsid", cfg.wifiSsid);
  cfg.wifiPass   = prefs.getString("wifiPass", cfg.wifiPass);
  cfg.callsign   = prefs.getString("callsign", cfg.callsign);
  cfg.aprsServer = prefs.getString("aprsHost", cfg.aprsServer);
  cfg.aprsPort   = prefs.getUShort("aprsPort", cfg.aprsPort);
  cfg.symTable   = (char)prefs.getUChar("symTbl", (uint8_t)cfg.symTable);
  cfg.symChar    = (char)prefs.getUChar("symChr", (uint8_t)cfg.symChar);
  cfg.beaconIntervalSec = prefs.getUShort("beaconSec", cfg.beaconIntervalSec);
  cfg.statusText        = prefs.getString("status", cfg.statusText);
  prefs.end();
}

void saveConfig() {
  prefs.begin("aprs", false);
  prefs.putString("wifiSsid", cfg.wifiSsid);
  prefs.putString("wifiPass", cfg.wifiPass);
  prefs.putString("callsign", cfg.callsign);
  prefs.putString("aprsHost", cfg.aprsServer);
  prefs.putUShort("aprsPort", cfg.aprsPort);
  prefs.putUChar("symTbl", (uint8_t)cfg.symTable);
  prefs.putUChar("symChr", (uint8_t)cfg.symChar);
  prefs.putUShort("beaconSec", cfg.beaconIntervalSec);
  prefs.putString("status", cfg.statusText);
  prefs.end();
}

void printConfig() {
  Serial.println(F("[配置] 当前设置:"));
  Serial.printf("  呼号    : %s (pass: %u)\n",
                cfg.callsign.c_str(),
                aprs_calculatePasscode(cfg.callsign.c_str()));
  Serial.printf("  APRS-IS : %s:%u\n",
                cfg.aprsServer.c_str(),
                cfg.aprsPort);
  Serial.printf("  WiFi    : %s / %s\n",
                cfg.wifiSsid.c_str(),
                cfg.wifiPass.c_str());
  Serial.printf("  符号    : %c %c\n",
                cfg.symTable,
                cfg.symChar);
  Serial.printf("  信标    : %u sec\n",
                cfg.beaconIntervalSec);

  String status = cfg.statusText;
  status.replace('\r', ' ');
  status.replace('\n', ' ');
  status.trim();
  Serial.printf("  状态    : %s\n", status.c_str());
}

